package models

import (
	"go-project/common"
)

type Permissions struct {
	ID          uint           `gorm:"primary_key" json:"id"`
	Code        string         `gorm:"type:varchar(255);not null;comment:'权限标识'" json:"code"`
	DisplayName string         `gorm:"type:varchar(255);not null;comment:'权限名称'" json:"display_name"`
	IsMenu      int8           `json:"is_menu"`
	Url         string         `gorm:"type:varchar(255);comment:'url'" json:"url"`
	Icon        string         `gorm:"type:varchar(255);comment:'icon'" json:"icon"`
	Sort        int8           `json:"sort"`
	ParentID    *uint          `gorm:"parent_id" json:"parent_id"`
	Parent      *Permissions   `gorm:"foreignKey:ParentID"`
	Children    []*Permissions `gorm:"foreignKey:ParentID"`
	Action      string         `json:"action"`
	Model
}

func (permissions *Permissions) TableName() string {
	return "permissions"
}

func (permissions *Permissions) CheckNameExist(name string, id uint) bool {
	query := common.DB.Where("display_name=?", name)
	if id != 0 {
		query = query.Not("id", id)
	}
	if query.First(permissions).RecordNotFound() {
		return false
	}
	return true
}

func (permissions *Permissions) CheckCodeExist(code string, id uint) bool {
	query := common.DB.Where("code=?", code)
	if id != 0 {
		query = query.Not("id", id)
	}
	if query.First(permissions).RecordNotFound() {
		return false
	}
	return true
}

func (permission *Permissions) GetChildrenPermissions(parentID uint, permissions *[]Permissions) error {
	var children []Permissions
	err := common.DB.Where("parent_id = ?", parentID).Find(&children).Error
	if err != nil {
		return err
	}

	for _, child := range children {
		*permissions = append(*permissions, child)
		err := permission.GetChildrenPermissions(child.ID, permissions)
		if err != nil {
			return err
		}
	}
	return nil
}
